package com.wondersgroup.tjfx.common.resultHandler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Component("funnel")
public class ChartFunnelResultHandler implements ResultSetExtractor<JSONObject> {

	@Override
	public JSONObject extractData(ResultSet rs) throws SQLException, DataAccessException {
		JSONObject ro = new JSONObject();
		ro.put("state", "true");
		JSONObject json = new JSONObject();
		ResultSetMetaData rm = null;
		rm = rs.getMetaData();
		JSONArray nameArr = new JSONArray();
		int length = 0;
		while (rs.next()) {
			length++;
			String name = rs.getString("NAME");
			nameArr.add(name);
			for (int i = 0; i < rm.getColumnCount(); i++) {
				/* 取字段名 */
				String columnName = rm.getColumnLabel(i + 1);
				columnName = columnName.toUpperCase();
				/* 取值 */
				String value = rs.getString(i + 1);
				value = value == null ? "" : value;
				if (json.containsKey(columnName)) {
					JSONArray ar = json.getJSONArray(columnName);
					JSONObject j = new JSONObject();
					j.put("name", name);
					j.put("value", value);
					ar.add(j);
				} else {
					JSONArray ar = new JSONArray();
					JSONObject j = new JSONObject();
					j.put("name", name);
					j.put("value", value);
					ar.add(j);
					json.put(columnName, ar);
				}
			}
		}
		json.remove("NAME");
		json.put("legend", nameArr);
		ro.putAll(json);
		if (length == 0) {
			ro.put("state", "kong");
		}
		return ro;
	}
}
